//
//  AboutViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-5-17.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

#import "AboutViewController.h"

#import "DataManager.h"


@implementation AboutViewController

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	// NSLocalizedString(@"KEY",@"Comment"); 这个宏 从默认名称的 .string 装载文字内容，如果是
	// 如果是自定义的名称，就需要调用 NSLocalizedStringFromTable(@"key",@"tablename",@"comment"); 来装载
	self.navigationItem.title = (NSLocalizedStringFromTable(@"ABOUT_IFLICK",@"main",@""));  // @"About iFlick";
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


/**
 * 刷新数据
 */
-(void)refreshInfo{
	[infoTable reloadData];
}


#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger ret = 0;
	switch (section) {
		case 0:
			ret = 3;
			break;
		case 1:
			// TODO Need Homepage
			//ret = 4;
			ret = 3;
			break;
		default:
			break;
	}
    return ret;
}

- (void)setInformationTitle:(NSInteger)row withCell:(UITableViewCell *)cell {
	NSString *version = nil;
	DataManager *dm;
	NSString *uname;
	switch (row) {
		case 0:
			version  = [[[NSBundle mainBundle] infoDictionary] valueForKey:[NSString stringWithFormat:@"CFBundleVersion"]];
			cell.textLabel.text = [NSString stringWithFormat:@"iFlick v%@",version];
			break;
		case 1:
			cell.textLabel.text = [NSString stringWithFormat:@"%@: %@",(NSLocalizedStringFromTable(@"AUTHOR",@"main",@"")),@"Zhang Xiaohe"];
			break;
		
		case 2:
			dm = [DataManager sharedDataManager];
			if([dm isAuthorized]){
				uname = [dm currentUserName];
			}else {
				uname = nil;
			}

			if(uname){
				cell.textLabel.text = [NSString stringWithFormat:@"Flickr Account: %@",uname];
			}else{
				cell.textLabel.text = [NSString stringWithFormat:@"Flickr Account: %@",(NSLocalizedStringFromTable(@"NO_LOGIN",@"main",@""))];
			}
			break;


		default:
			// TODO 设置
			cell.textLabel.text = @"Cell Need";
			break;
	}
}


- (void)setWebsites:(NSInteger)row withCell:(UITableViewCell *)cell {
	switch (row) {
		//case 0:
//#ifndef __IPHONE_3_0
//			cell.text = [NSString stringWithString:(NSLocalizedStringFromTable(@"HOMEPAGE",@"main",@""))];
//#else
//			cell.textLabel.text = [NSString stringWithString:(NSLocalizedStringFromTable(@"HOMEPAGE",@"main",@""))];
//#endif
//			break;
		case 0:
			cell.textLabel.text = @"flickr.com";
			break;
		case 1:
			cell.textLabel.text = (NSLocalizedStringFromTable(@"TELL_FRIEND",@"main",@""));
			break;
		case 2:
			cell.textLabel.text = (NSLocalizedStringFromTable(@"FEEDBACK",@"main",@""));
			break;
		default:
			// TODO 设置
			cell.textLabel.text = @"Cell Need";
			break;
	}
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	
	NSString *fn = nil;
	fn = [cell.textLabel.font.fontName copy];
	
	UIFont *nf = [UIFont fontWithName:fn size:13.0f];
	cell.textLabel.font = nf;
	[fn release];
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	
	switch (section) {
		case 0:
			// 对于第一个section 都不能够选择
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			[self setInformationTitle:row withCell:cell];
			break;
		case 1:
			[self setWebsites:row withCell:cell];
			break;

		default:
			break;
	}
	
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSString *ret = nil;
	switch (section) {
		case 0:
			ret = (NSLocalizedStringFromTable(@"SOFT_INFO",@"main",@""));
			break;
		case 1:
			ret = (NSLocalizedStringFromTable(@"WEBSITE",@"main",@""));
			break;

		default:
			break;
	}
	return ret;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	//UIViewController *about = [[ViewControllerChooser sharedChooser] choose:VCC_ID_ABOUT];
	//	[self.navigationController pushViewController:about animated:YES];
	
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	BOOL bOK;
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	MFMailComposeViewController *mailController;
	BOOL cansend;
	// Website 部分
	if(section == 1){
		switch (row) {
			case 0:
				// TODO 访问flickr.com
				bOK = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://m.flickr.com"]];
				break;
			case 1:
				// TODO 针对直接设定 mailto:的，能够开启邮件客户端，在真机上可以开启
				//bOK = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:"]];
				cansend = [MFMailComposeViewController canSendMail];
				if(cansend){
					mailController = [[[MFMailComposeViewController alloc] init] autorelease];
					[mailController setSubject:@"Hi, iFlick is a good flickr uploader"];
					[mailController setMessageBody:@"I have download this app for upload and share photos, <br/><a href=\"http://itunes.apple.com/us/app/iflick/id321342780?mt=8&uo=6\" target=\"itunes_store\"><img height=\"15\" width=\"61\" alt=\"iFlick\" src=\"http://ax.phobos.apple.com.edgesuite.net/images/badgeitunes61x15dark.gif\" /></a>" isHTML:YES];
					mailController.mailComposeDelegate = self;
					[self presentModalViewController:mailController animated:NO];
				}
				break;
				
			case 2:
				//bOK = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:vhly@163.com?subject=iFlick%20Bug%20Report"]];
				cansend = [MFMailComposeViewController canSendMail];
				if(cansend){
					mailController = [[[MFMailComposeViewController alloc] init] autorelease];
					[mailController setSubject:@"Feedback for iFlick"];
					[mailController setToRecipients:[NSArray arrayWithObject:@"vhly@163.com"]];
					mailController.mailComposeDelegate = self;
					[self presentModalViewController:mailController animated:NO];
				}
				break;

			default:
				break;
		}
	}
}

#pragma mark -
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController*)controller
		  didFinishWithResult:(MFMailComposeResult)result
						error:(NSError*)error{
    // Notifies users about errors associated with the interface
	UIAlertView *alert = nil;
    switch (result)
    {
        case MFMailComposeResultCancelled:
            break;
        case MFMailComposeResultSaved:
			alert = [[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"CONFIRM",@"main",@"") message:NSLocalizedStringFromTable(@"MAILSAVED",@"main",@"") delegate:nil cancelButtonTitle:NSLocalizedStringFromTable(@"CANCEL",@"main",@"") otherButtonTitles:nil];
			[alert show];
			[alert release];
            break;
        case MFMailComposeResultSent:
			NSLog(@"mail sent");
            break;
        case MFMailComposeResultFailed:
			NSLog(@"mail failed");
			alert = [[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"ERROR",@"main",@"") message:[error description] delegate:nil cancelButtonTitle:NSLocalizedStringFromTable(@"CANCEL",@"main",@"") otherButtonTitles:nil];
			[alert show];
			[alert release];
            break;
        default:
            break;
    }
    //[self dismissModalViewControllerAnimated:YES];
	[controller dismissModalViewControllerAnimated:YES];	
}


- (void)dealloc {
    [super dealloc];
}


@end
